package com.demo.web.modules.auth;

import com.alibaba.fastjson.JSONObject;
import com.demo.common.util.bean.TokenUtilsTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final String token = "token#";

    /**
     * 在请求处理之前进行调用，在进入Controller方法之前先进入此方法
     * 返回true才会继续向下执行，返回false取消当前请求
     * 登录拦截，权限资源控制工作
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        String userAccount = null;
        String redirectUrl = "login";

        if ((httpServletRequest.getParameter("language") != null &&
                !httpServletRequest.getParameter("language").equals("en"))) {
            redirectUrl += "_en";
        }

        //从cookie中取值
        Cookie[] cookies = httpServletRequest.getCookies();

        //从http请求头中取出 token
        String token1 = httpServletRequest.getHeader("Authorization");
        //System.out.print(token1);
        if (token1 != null) {
            boolean result = TokenUtilsTool.verify(token1);
            if (result) {
                System.out.println("通过拦截器");
                return true;
            }
        }
        try {
            JSONObject json = new JSONObject();
            json.put("code", "401");
            json.put("message", "No authentication");
            json.put("data", "");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            out = httpServletResponse.getWriter();
            out.append(json.toString());
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject json = new JSONObject();
            json.put("code", "500");
            json.put("msg", "Server error");
            json.put("data", "");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            out = httpServletResponse.getWriter();
            out.append(json.toString());
            System.out.println("Token校验失败！");
            return false;
        }
    }
}

